﻿using System;
using System.IO;
using System.Net;

namespace MiniX.Utility.Helper
{
    /// <summary>
    /// 生成微信小程序二维码-用于分享
    /// </summary>
	public class WXQRCode
	{
		public WXQRCode()
		{

		}

        /// <summary>
        /// 生成微信小程序二维码
        /// </summary>
        /// <param name="wxmini_path">微信小程序页面路由</param>
        /// <param name="save_path">保存本地路径</param>
        /// <param name="width">宽度（建议1280）</param>
        public static void GetQRCodePath(string wxmini_path, string save_path, int width)
        {
            var access_token = WeChatAppDecrypt.GetAccessToken(Pay.WeChat.WeChatConfig.APPID, Pay.WeChat.WeChatConfig.SERCRET);
            string json = "";
            string url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + access_token;

            json = "{";
            json += string.Format("\"path\":\"{0}\",", wxmini_path);
            json += string.Format("\"width\":\"{0}\"", width);
            json += "}";

            // DataJson的配置见小程序开发文档，B接口：https://mp.weixin.qq.com/debug/wxadoc/dev/api/qrcode.html
            CreatedQRCode(url, json, save_path);
        }

        /// <summary>
        /// 返回生成后的二维码图片路径
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="save_path">保存本地路径</param>
        public static void CreatedQRCode(string url, string param, string save_path)
        {
            string strURL = url;
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            string paraUrlCoded = param;
            byte[] payload;
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            request.ContentLength = payload.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();
            System.Net.HttpWebResponse response;
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream s;
            s = response.GetResponseStream();
            byte[] stb = StreamToBytes(s);
            System.IO.File.WriteAllBytes(save_path, stb);
        }

        /// <summary>
        /// 将数据流转为byte[]
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static byte[] StreamToBytes(Stream stream)
        {
            List<byte> bytes = new List<byte>();
            int temp = stream.ReadByte();
            while (temp != -1)
            {
                bytes.Add((byte)temp);
                temp = stream.ReadByte();
            }
            return bytes.ToArray();
        }
    }
}

